package com.stark.resume.lib.utils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPostUtil {
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build();

    public interface PostCallback {
        void onSuccess(String response);

        void onFailure(Exception e);
    }

    // 表单POST请求
    public static void postForm(String url, Map<String, String> params, PostCallback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        executeRequest(new Request.Builder()
                .url(url)
                .post(builder.build())
                .build(), callback);
    }

    // JSON POST请求
    public static void postJson(String url, String json, PostCallback callback) {
        executeRequest(new Request.Builder()
                .url(url)
                .post(RequestBody.create(json, JSON))
                .build(), callback);
    }

    private static void executeRequest(Request request, PostCallback callback) {
        client.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    if (!response.isSuccessful()) {
                        throw new IOException("Unexpected code: " + response);
                    }
                    callback.onSuccess(response.body().string());
                } catch (Exception e) {
                    callback.onFailure(e);
                }
            }
        });
    }
}
